<template>
  <div>
    <Card dis-hover :bordered="false" class="ivu-mt">
      <jgsearch
        :searchData="searchData"
        @on-enter="askDatasearch"
        @on-clear="askDatasearch"
        @on-change-change="askDatachanges"
        @on-change-changecheck="askDatacheck"
        @on-change-changeAlias="changeAlias"
      />
      <Table
        highlight-row
        ref="table"
        :columns="columns"
        :max-height="600"
        :data="list"
        :loading="loading"
        size="small"
      >
        <template slot-scope="{ row }" slot="clueState">
          <div v-if="row.status_name">
            <Tag v-if="+row.clue_status_id === 7" color="primary">{{
              row.status_name
            }}</Tag>
            <Tag v-else-if="+row.clue_status_id === 8" color="success">{{
              row.status_name
            }}</Tag>
            <Tag v-else-if="+row.clue_status_id === 6" color="default">{{
              row.status_name
            }}</Tag>
            <Tag v-else-if="+row.clue_status_id === 9" color="warning">{{
              row.status_name
            }}</Tag>
            <Tag v-else>{{ row.status_name }}</Tag>
          </div>
        </template>
        <template slot-scope="{ row }" slot="callState">
          <Badge
            v-if="row.is_call_str === '未接听'"
            status="warning"
            text="未接听"
          />
          <Badge
            v-if="row.is_call_str === '已接听'"
            status="success"
            text="已接听"
          />
        </template>
        <template slot-scope="{ row }" slot="operation">
          <a
            v-hasC="{
              name: 'clue-call-contact',
              flag: 'v1/clue/call/contact',
            }"
            v-if="+row.clue_status_id !== 8"
            @click="handleContactClue(row)"
            >联系</a
          >
          <span v-else class="person">{{ row.realname }}</span>
          <Divider type="vertical"></Divider>
          <a @click="handleSound(row)">听录音</a>
          <Divider
            v-if="row.repeat_type === '1'"
            v-hasC="{
              name: 'v1-patient-index-repeat-list7',
              flag: 'v1/patient/index/repeat-list',
            }"
            type="vertical"
          ></Divider>
          <a
            v-if="row.repeat_type === '1'"
            v-hasC="{
              name: 'v1-patient-index-repeat-list7',
              flag: 'v1/patient/index/repeat-list',
            }"
            @click="repeatData(row)"
            >重复</a
          >
        </template>
      </Table>
      <div class="ivu-mt ivu-text-center">
        <Page
          show-total
          show-elevator
          show-sizer
          :total="total"
          :current.sync="params.page"
          :page-size="params.pageSize"
          :page-size-opts="pageOpts"
          @on-change="changepage"
          @on-page-size-change="changepageSize"
        />
      </div>
    </Card>
    <Modal
      title="听录音"
      v-model="sound"
      :mask-closable="false"
      width="360"
      footer-hide
      @on-cancel="cancel"
    >
      <audio :src="musicurl" controls id="audio" v-if="musicurl != ''"></audio>
      <div v-else>暂无录音</div>
      <div v-if="musicurl != ''" style="margin-top: 10px;">
        播放倍速：
        <RadioGroup v-model="model1" @on-change="changeaudio(model1)">
          <Radio :label="item.id" v-for="item in RadioGroup" :key="item.id">{{
            item.name
          }}</Radio>
        </RadioGroup>
      </div>
    </Modal>
    <Modal
      ref="contact"
      title="联系线索客户"
      v-model="contactClue"
      :mask-closable="false"
      width="1000"
      @on-cancel="handleDrawerCancel('formItem')"
    >
      <DescriptionList :col="2">
        <Description term="来电号码：">{{ createData.called_tel }}</Description>
        <Description term="来电时间：">{{ createData.call_time }}</Description>
        <Description term="来电状态：">{{
          createData.is_call_str
        }}</Description>
        <Description term="通话时长：">{{
          createData.duration_str
        }}</Description>
      </DescriptionList>
      <Divider></Divider>
      <Form
        label-position="top"
        :model="params1"
        ref="formItem"
        :rules="createRuless"
      >
        <Row>
          <Col span="8">
            <FormItem label="联系结果">
              <RadioGroup
                v-model="params1.clue_status_id"
                @on-change="changeclue"
              >
                <Radio
                  :label="item.value"
                  v-for="item in clueList"
                  :key="item.value"
                  v-if="+item.value !== 9"
                  ><span>{{ item.label }}</span></Radio
                >
              </RadioGroup>
            </FormItem>
            <Timeline
              style="max-height: 380px; overflow: auto;"
              v-if="contact.length"
            >
              <TimelineItem v-for="item in contact" :key="item.id">
                <p class="time ivu-mb-8">{{ item.created_at }}</p>
                <p class="content ivu-mb-8">{{ item.remark }}</p>
                <p class="consultant ivu-mb-8">
                  <span class="c-inr ivu-mr-8">{{ item.realname }}</span>
                  <Badge
                    v-if="item.status_name === '未联系上'"
                    status="success"
                    :text="item.status_name"
                  />
                  <Badge
                    v-if="item.status_name === '无效'"
                    status="processing"
                    :text="item.status_name"
                  />
                  <Badge
                    v-if="item.status_name === '转客户'"
                    status="warning"
                    :text="item.status_name"
                  />
                  <Badge
                    v-if="item.status_name === '新数据'"
                    status="default"
                    :text="item.status_name"
                  />
                </p>
              </TimelineItem>
            </Timeline>
          </Col>
          <Col span="16">
            <template v-if="params1.clue_status_id === '8'">
              <Row :gutter="24">
                <Col span="5">
                  <FormItem label="姓名">
                    <Input
                      v-model="params1.userName"
                      placeholder="请输入姓名"
                    />
                  </FormItem>
                </Col>
                <Col span="6">
                  <FormItem label="性别">
                    <RadioGroup v-model="params1.sex">
                      <Radio :label="0">未知</Radio>
                      <Radio :label="1">男</Radio>
                      <Radio :label="2">女</Radio>
                    </RadioGroup>
                  </FormItem>
                </Col>
                <Col span="4">
                  <FormItem label="年龄" prop="age">
                    <InputNumber
                      :max="100"
                      :min="1"
                      v-model="params1.age"
                    ></InputNumber>
                  </FormItem>
                </Col>
                <Col span="9">
                  <FormItem label="城市" required>
                    <!-- <Select ref="citySearch" v-model="params1.city" placeholder="请输入城市拼音简写" filterable
                                    remote clearable :remote-method="remoteMethod" :loading="loadingcity">
                                    <Option v-for="item in optionscity" :value="item.value" :key="item.value">{{
                                        item.label }}</Option>
                                </Select> -->
                    <jgcheckcity
                      ref="checkcity"
                      v-if="cityshow"
                      @cityvalue="cityvalue"
                      v-model="city_id"
                      :name="`call`"
                    />
                  </FormItem>
                </Col>
              </Row>
              <Row :gutter="24">
                <Col span="8">
                  <FormItem label="手机号" prop="mobile">
                    <Input
                      v-model="params1.mobile"
                      @on-keyup="
                        params1.mobile = params1.mobile.replace(
                          /\s+|[\r\n]/g,
                          ''
                        )
                      "
                      @on-blur="telrepeat(params1.mobile)"
                      placeholder="请输入手机号"
                    />
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem label="微信号">
                    <Input
                      v-model="params1.weChartNum"
                      @on-keyup="
                        params1.weChartNum = params1.weChartNum.replace(
                          /\s+|[\r\n]/g,
                          ''
                        )
                      "
                      @on-blur="WXrepeat(params1.weChartNum)"
                      placeholder="请输入微信号"
                    />
                  </FormItem>
                </Col>
              </Row>
              <Row :gutter="24">
                <Col span="8">
                  <FormItem label="一级病种" prop="oneDiseases">
                    <Select
                      placeholder="请选择一级病种"
                      v-model="params1.oneDiseases"
                      clearable
                      :key="Math.random() * 10 + 1"
                      @on-clear="clearOne"
                      @on-change="changeOne"
                    >
                      <Option
                        v-for="item in diseasesArr1"
                        :value="item.value"
                        :key="item.value"
                        >{{ item.label }}</Option
                      >
                    </Select>
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem
                    label="二级病种"
                    :key="Math.random() * 10 + 1"
                    prop="twoDiseases"
                    :rules="twoRules"
                    v-show="diseasesArr2.length > 0"
                  >
                    <Select
                      placeholder="请选择二级病种"
                      v-model="params1.twoDiseases"
                      clearable
                    >
                      <Option
                        v-for="item in diseasesArr2"
                        :value="item.value"
                        :key="item.value"
                        >{{ item.label }}</Option
                      >
                    </Select>
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem label="患者状态" prop="patientStatus">
                    <Select
                      placeholder="请选择"
                      v-model="params1.patientStatus"
                      clearable
                    >
                      <Option
                        v-for="item in patientStatusArr"
                        :value="item.value"
                        :disabled="+item.is_select === 0"
                        :key="item.value"
                        >{{ item.label }}</Option
                      >
                    </Select>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span="12">
                  <FormItem label="部位" prop="bodyPart" :rules="bodyPartRule">
                    <TreeSelect
                      :max-tag-count="2"
                      v-model="params1.bodyPart"
                      :data="postList"
                      clearable
                      multiple
                    />
                  </FormItem>
                </Col>
              </Row>
              <template
                v-if="
                  +params1.patientStatus === 2 || +params1.patientStatus === 1
                "
              >
                <FormItem label="下次回访时间" prop="day">
                  <Row :gutter="16">
                    <Col span="6">
                      <InputNumber
                        :formatter="$inputday"
                        :step="1"
                        :min="0"
                        v-model.number="params1.day"
                        @on-change="blurday(params1.day)"
                      >
                      </InputNumber>
                    </Col>
                    <Col span="4">天后</Col>
                    <Col span="12">
                      <DatePicker
                        :editable="false"
                        :options="optionss"
                        type="date"
                        v-model="DatePicker"
                        @on-change="changeday(DatePicker)"
                        placeholder="请输入回访时间"
                      >
                      </DatePicker>
                    </Col>
                  </Row>
                </FormItem>
              </template>
              <template v-if="+params1.patientStatus === 1">
                <FormItem label="预到时间" prop="day1">
                  <Row :gutter="16">
                    <Col span="6">
                      <InputNumber
                        :formatter="$inputday"
                        :step="1"
                        :min="0"
                        v-model.number="params1.day1"
                        @on-change="blurday1(params1.day1)"
                      >
                      </InputNumber>
                    </Col>
                    <Col span="4">天后</Col>
                    <Col span="12">
                      <DatePicker
                        :editable="false"
                        :options="optionss"
                        type="date"
                        v-model="DatePicker1"
                        @on-change="changeday1(DatePicker1)"
                        placeholder="请输入预到时间"
                      >
                      </DatePicker>
                    </Col>
                  </Row>
                </FormItem>
              </template>
            </template>
            <FormItem label="备注" prop="remark" :rules="remarkRule">
              <Input
                type="textarea"
                placeholder="请备注原因"
                v-model="params1.remark"
                :autosize="{ minRows: 2, maxRows: 8 }"
              />
            </FormItem>
          </Col>
        </Row>
      </Form>

      <div slot="footer">
        <Button @click="handleDrawerCancel('formItem')">取消</Button>
        <Button
          type="primary"
          :loading="remarksloading"
          @click="handlesearch('formItem')"
          >确定</Button
        >
      </div>
    </Modal>
    <Modal
      title="重复数据"
      :mask-closable="false"
      footer-hide
      :width="80"
      v-model="repeatDatas"
    >
      <Table
        :max-height="400"
        :columns="repeatColumns"
        :data="repeatDataList"
        :loading="callloading"
      >
        <template slot="mobile" slot-scope="{ row }">
          <span
            v-if="+repeatInfo.repeat_type === 1"
            :class="
              row.mobile && row.mobile === repeatInfo.mobile
                ? 'repeatColor'
                : null
            "
          >
            {{ row.mobile }}
          </span>
          <span v-else>{{ row.mobile }}</span>
        </template>
      </Table>
    </Modal>
  </div>
</template>
<script>
import jgsearch from "@/components/search";
// import jgcheckcity from "@/components/checkcity";
import {
  cluecallselectinfo,
  cluecalllist,
  cluecallcontact,
  getCluecallcontact,
} from "@api/hqapi/indexone";
import {
  patientindexsearchcity,
  repeatCallData,
  patientindexsearchmobile,
} from "@api/hqapi";
import dayjs from "dayjs";
let lodash = require("lodash");

export default {
  name: "calls",
  components: { jgsearch },
  data() {
    const validateMobile = (rule, value, callback) => {
      if (value === "") {
        callback();
      } else {
        let reg = /^\d{10,12}$/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的联系号码"));
        }
      }
    };
    return {
      city_id: [],
      cityshow: true,
      optionscity: [],
      callloading: false,
      repeatDatas: false,
      edit: false,
      device: [],
      loading: false,
      loadingcity: false,
      repeatColumns: Object.freeze([
        {
          title: "设备别名",
          key: "wechatid",
          width: 180,
        },
        {
          title: "归属部门",
          key: "department_name",
        },
        {
          title: "来电号码",
          slot: "mobile",
        },
        {
          title: "通话时长",
          key: "duration_str",
        },
        {
          title: "线索状态",
          key: "status_name",
        },
        {
          title: "来电时间",
          key: "call_time",
        },
      ]),
      postList: [],
      createRuless: {
        remark: [
          {
            required: true,
            type: "string",
            message: "请输入备注原因",
            trigger: "blur",
          },
        ],
        mobile: [{ validator: validateMobile, trigger: "blur" }],

        city: [
          {
            required: true,
            message: "请选择城市",
            trigger: "change",
          },
        ],
        age: [
          {
            required: true,
            message: "请填写年龄",
            type: "number",
            trigger: "blur,change",
          },
        ],
        oneDiseases: [
          {
            required: true,
            message: "请选择一级病种",
            trigger: "change",
          },
        ],
        twoDiseases: [
          {
            required: true,
            message: "请选择二级病种",
            trigger: "change",
          },
        ],
        patientStatus: [
          {
            required: true,
            message: "请选择患者状态",
            trigger: "change",
          },
        ],
        day: [
          {
            required: true,
            type: "number",
            message: "请输入回访时间",
            trigger: "blur",
          },
        ],
        day1: [
          {
            required: true,
            type: "number",
            message: "请输入预约",
            trigger: "blur",
          },
        ],
      },
      dateDay: ["2020-05-01", "2020-05-01"],
      list: [],
      selectedData: [],
      current: 1,
      size: 10,
      showCreate: false,
      creating: true,
      remarksloading: false,
      updateIndex: -1,
      contactClue: false,
      sound: false,
      diseasesArr1: [],
      diseasesArr2: [],
      createData: {
        baisc: "",
        name: "",
        phone: "",
        wx: "",
        age: 1,
        gender: "",
        post: [],
        label: [],
        remarks: "",
      },
      columns: [
        {
          title: "设备别名",
          key: "device_name",
          fixed: "left",
          width: 130,
        },
        { title: "归属部门", key: "department_name", width: 100 },
        { title: "来电号码", key: "called_tel", width: 120 },
        { title: "通话时长", key: "duration_str", width: 100 },
        { title: "来电时间", key: "call_time", width: 168 },
        { title: "来电状态", slot: "callState", width: 100 },
        { title: "线索状态", slot: "clueState", width: 108 },
        { title: "处理时间", key: "deal_time", width: 150 },
        {
          title: "联系人员",
          key: "operation_name",
          minWidth: 120,
          ellipsis: true,
          tooltip: true,
        },
        { title: "备注", key: "customer_remark", minWidth: 150 },
        {
          title: "操作",
          key: "operation",
          slot: "operation",
          fixed: "right",
          width: 180,
        },
      ],
      contact: [],
      searchData: {
        project: [
          {
            id: 1,
            key: "Input",
            clearable: true,
            placeholder: "请输入手机号",
            clearable: true,
            style: { width: "200px" },
            value: "",
          },
          {
            id: 2,
            key: "Select",
            clearable: true,
            placeholder: "线索状态",
            style: { width: "100px" },
            value: "",
            childList: [],
            callback: "change",
          },
          {
            id: 3,
            key: "Select",
            clearable: true,
            placeholder: "部门",
            style: { width: "100px" },
            value: "",
            childList: [],
            callback: "changeAlias",
          },
          {
            id: 11,
            key: "Select",
            clearable: true,
            placeholder: "设备别名",
            style: { width: "200px" },
            value: "",
            childList: [],
            callback: "change",
            show: {
              key: false,
            },
          },
          {
            id: 4,
            key: "Select",
            clearable: true,
            placeholder: "来电状态",
            style: { width: "100px" },
            value: "",
            childList: [
              { value: 1, label: "已接听" },
              { value: 0, label: "未接听" },
            ],
            callback: "change",
          },
          {
            id: 6,
            key: "Select",
            clearable: true,
            placeholder: "联系人员",
            style: { width: "100px" },
            value: "",
            childList: [],
            callback: "change",
          },
          {
            id: 5,
            key: "DatePicker",
            type: "daterange",
            options: {
              disabledDate(date) {
                return date && date.valueOf() > Date.now();
              },
            },
            placeholder: "请选择来电日期",
            style: { width: "200px" },
            value: [new Date(), new Date()],
            callback: "change",
          },
          {
            id: 8,
            key: "Checkbox",
            style: { width: "100px" },
            value: [],
            childList: [{ label: "重复", value: 3 }],
            callback: "changecheck",
          },
        ],
      },
      total: 0,
      DatePicker: new Date(new Date().getTime() + 86400000),
      DatePicker1: new Date(new Date().getTime()),
      optionss: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 24 * 3600 * 1000;
        },
      },
      pageOpts: [10, 15, 20, 30, 50],
      params1: {
        id: undefined,
        clue_status_id: "8",
        remark: "",
        day: 1,
        bodyPart: [],
        weChartNum: "",
        mobile: "",
        day1: 0,
        userName: "",
        age: null,
        birthday: "",
        sex: "",
        city_id: "",
        oneDiseases: "",
        twoDiseases: "",
        patientStatus: "2",
      },
      patientStatusArr: [],
      params: {
        page: 1,
        pageSize: 10,
        mobile: "",
        clue_status_id: "",
        wechatid: "",
        department_id: "",
        is_call: "",
        have_repeat: 0,
        operation_id: "",
        start_time: new Date(),
        end_time: new Date(),
      },
      RadioGroup: [
        { id: 0.5, name: "0.5" },
        { id: 0.75, name: "0.75" },
        { id: 1, name: "1.0" },
        { id: 1.5, name: "1.5" },
        { id: 1.75, name: "1.75" },
        { id: 2, name: "2.0" },
      ],
      model1: 1,
      clueList: [],
      contactDatas: true,
      musicurl: "",
      repeatDataList: [],
      repeatInfo: {},
    };
  },
  mounted() {
    this.initial();
  },
  computed: {
    bodyPartRule() {
      if (this.params1.oneDiseases === "1") {
        return {
          required: true,
          validator: (rule, value, callback) => {
            if (value.length) {
              callback();
            } else {
              callback(new Error("请选择部位"));
            }
          },
          trigger: "change",
        };
      } else {
        return {
          required: false,
          type: "array",
          trigger: "change",
        };
      }
    },
    remarkRule() {
      if (this.params1.clue_status_id === "8") {
        return {
          required: false,
          type: "string",
          message: "请输入备注原因",
          trigger: "blur",
        };
      } else {
        return {
          required: true,
          type: "string",
          message: "请输入备注原因",
          trigger: "blur",
        };
      }
    },
    twoRules() {
      if (this.diseasesArr2.length) {
        return {
          required: true,
          message: "请选择二级病种",
          trigger: "change",
        };
      } else {
        return {
          required: false,
          message: "请选择二级病种",
          trigger: "change",
        };
      }
    },
    birthdays() {
      if (this.params1.age !== "") {
        var year = new Date().getFullYear() - this.params1.age;
        return year + "-01" + "-01";
      }
    },
  },
  methods: {
    cityvalue(city) {
      this.city_id = city;
      this.params1.city_id = city.join(",");
      // this.askData();
    },
    repeatData(data) {
      this.repeatDatas = true;
      this.callloading = true;
      repeatCallData({
        id: data.id,
      }).then((res) => {
        this.repeatDataList = res.list;
        this.repeatInfo = res.info;
        this.callloading = false;
      });
    },
    clearOne() {
      this.diseasesArr2 = [];
      this.params1.twoDiseases = "";
    },
    initial() {
      cluecallselectinfo().then((res) => {
        this.clueList = res.clue_status;
        this.device = res.device;
        this.searchData.project.forEach((item) => {
          if (item.id === 2) {
            item.childList = res.clue_status;
          } else if (item.id === 3) {
            item.childList = res.department;
          } else if (item.id === 6) {
            item.childList = res.operation_member;
          }
        });
      });
      this.askData();
    },
    askData() {
      cluecalllist(this.params).then((res) => {
        this.list = Object.freeze(res.list);
        this.total = res.total;
      });
    },
    changeAlias(value) {
      this.params.wechatid = "";
      if (value) {
        let childLis = this.device
          .filter((ee) => ee.did === value)
          .map((eee) => {
            return {
              ...eee,
              value: eee.wechatid,
              label: eee.nickname,
            };
          });
        this.searchData.project.forEach((item) => {
          if (item.id === 11) {
            item.value = "";
            // if (childLis.length) {
            item.show["key"] = true;
            item.childList = childLis;
            // } else {
            // item.show["key"] = false;
            // item.childList = [];
            this.askDatachanges();
            // }
          }
        });
      } else {
        this.searchData.project.forEach((item) => {
          if (item.id === 11) {
            item.show["key"] = false;
            item.childList = [];
            if (!item.value || item.value === undefined) {
              this.askDatachanges();
            } else {
              item.value = "";
            }
          }
        });
      }
    },
    /* @函数功能: 分页 */
    changepage(e) {
      this.params.page = e;
      this.askData();
    },
    /* @函数功能: 每页数量 */
    changepageSize(e) {
      this.params.pageSize = e;
      this.askData();
    },
    changeclue(e) {
      for (let item of this.clueList) {
        if (e === item.value) {
          if (+item.value === 8) this.contactDatas = true;
          else this.contactDatas = false;
        }
      }
    },
    changeOne(value) {
      if (value) {
        this.diseasesArr2 = this.diseasesArr1.filter(
          (ee) => ee.value == value
        )[0].children;
        this.params1.twoDiseases = "";
        if (!this.diseasesArr2.length) {
          this.$nextTick(() => {
            this.$refs.formItem.validateField("twoDiseases");
          });
        }
      }
    },
    askDatasearch() {
      this.searchData.project.forEach((item) => {
        if (item.key === "Input") {
          this.params.mobile = item.value;
          if (item.value !== "") {
            this.searchData.project.forEach((items) => {
              if (items.key === "DatePicker") {
                if (JSON.stringify(items.value) !== JSON.stringify(["", ""])) {
                  let timer = [
                    this.$Date(items.value[0]).format("YYYY-MM-DD"),
                    this.$Date(items.value[1]).format("YYYY-MM-DD"),
                  ];
                  this.storage.set("clue-call", timer);
                  items.value = ["", ""];
                  this.params.start_time = "";
                  this.params.end_time = "";
                }
              }
            });
          } else {
            this.searchData.project.forEach((items) => {
              if (items.key === "DatePicker") {
                if (
                  JSON.stringify(this.storage.get("clue-call")) !==
                  JSON.stringify(["", ""])
                ) {
                  items.value = this.storage.get("clue-call");
                  this.params.start_time = items.value[0];
                  this.params.end_time = items.value[1];
                }
              }
            });
          }
        }
      });
      this.params.page = 1;
      this.params.pageSize = 15;
      this.params.clue_status_id = "";
      this.params.department_id = "";
      this.params.is_call = "";
      this.params.operation_id = "";
      this.params.wechatid = "";
      this.askData();
    },
    askDatachanges() {
      this.params.page = 1;
      this.searchData.project.forEach((item) => {
        if (item.id === 2) {
          this.params.clue_status_id = item.value;
        } else if (item.id === 3) {
          this.params.department_id = item.value;
        } else if (item.id === 4) {
          this.params.is_call = item.value;
        } else if (item.id === 5) {
          this.params.start_time = item.value[0];
          this.params.end_time = item.value[1];
          let timer = ["", ""];
          if (JSON.stringify(item.value) !== JSON.stringify(["", ""])) {
            timer = [
              this.$Date(item.value[0]).format("YYYY-MM-DD"),
              this.$Date(item.value[1]).format("YYYY-MM-DD"),
            ];
          }
          this.storage.set("clue-call", timer);
        } else if (item.id === 6) {
          this.params.operation_id = item.value;
        } else if (item.id === 11) {
          this.params.wechatid = item.value;
        }
      });
      this.askData();
    },
    // 听录音
    handleSound(row) {
      this.musicurl = row.record_url;
      this.sound = true;
    },
    telrepeat(data) {
      let config = {
        id: this.params1.id === undefined ? 0 : this.params1.id,
        mobile: data,
      };
      patientindexsearchmobile(config).then((res) => {
        if (+res.result === 1) {
          this.$Message.error({
            duration: 2.5,
            content: "该手机号码已存在",
          });
        }
      });
    },
    WXrepeat(data) {
      let config = {
        id: this.params1.id === undefined ? 0 : this.params1.id,
        wechat_id: data,
      };

      patientindexsearchmobile(config).then((res) => {
        if (+res.result === 2) {
          this.$Message.error({
            duration: 2.5,
            content: "该微信号已存在",
          });
        }
      });
    },
    // 联系线索客户
    handleContactClue(row) {
      this.$refs.formItem.resetFields();
      (this.cityshow = false),
        getCluecallcontact({ id: row.id }).then((res) => {
          if (res.default_city && JSON.stringify(res.default_city) !== "{}") {
            this.optionscity = [
              {
                value: res.default_city.city_id,
                label: res.default_city.city_name,
              },
            ];
            // this.params1.city = res.default_city.city_id;
            this.params1.city_id = [];
            this.cityshow = true;
          }
          this.contact = res.contact;
          this.postList = res.body_parts_list;
          this.diseasesArr1 = res.diseases;
          this.patientStatusArr = res.patient_status;
        });
      this.contactClue = true;
      this.params1.id = row.id;
      this.params1.mobile = row.called_tel;
      this.params1.patientStatus = "2";
      this.createData = row;
      this.params1.city = [];
    },
    handleDrawerCancel(name) {
      this.city_id = [];
      this.$refs[name].resetFields();
      this.contactClue = false;
      this.params1 = {
        id: undefined,
        clue_status_id: "8",
        remark: "",
        day: 1,
        day1: 0,
        userName: "",
        weChartNum: "",
        mobile: "",
        age: null,
        birthday: "",
        sex: "",
        city_id: "",
        oneDiseases: "",
        twoDiseases: "",
        patientStatus: "2",
      };
      this.diseasesArr2 = [];
      this.diseasesArr1 = [];
    },
    // 搜索手机号
    handlesearch(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.params1.clue_status_id === "8") {
            let config = {
              id: this.params1.id === undefined ? 0 : this.params1.id,
              mobile: this.params1.mobile,
              wechat_id: this.params1.weChartNum,
            };
            patientindexsearchmobile(config).then((res) => {
              if (+res.result === 1) {
                this.$Modal.confirm({
                  title: "提示",
                  content: `<p>该手机号码已存在，是否继续录入?</p>`,
                  onOk: () => {
                    this.handleSubmit();
                  },
                  onCancel: () => {
                    this.remarksloading = false;
                  },
                });
              } else if (+res.result === 2) {
                this.$Modal.confirm({
                  title: "提示",
                  content: `<p>该微信号已存在，是否继续录入?</p>`,
                  onOk: () => {
                    this.handleSubmit();
                  },
                  onCancel: () => {
                    this.remarksloading = false;
                  },
                });
              } else if (+res.result === 3) {
                this.$Modal.confirm({
                  title: "提示",
                  content: `<p>该手机号/微信号已存在，是否继续录入?</p>`,
                  onOk: () => {
                    this.handleSubmit();
                  },
                  onCancel: () => {
                    this.remarksloading = false;
                  },
                });
              } else {
                this.handleSubmit();
              }
            });
          } else {
            this.handleSubmit();
          }
        }
      });
    },
    handleSubmit(name) {
      let params = {
        id: this.params1.id,
        clue_status_id: this.params1.clue_status_id,
        remark: this.params1.clue_status_id === "8" ? "" : this.params1.remark,
        day:
          this.params1.clue_status_id === "8" &&
          (this.params1.patientStatus === "2" ||
            this.params1.patientStatus === "1")
            ? parseInt(new Date(this.DatePicker).getTime() / 1000)
            : "",
        type: 3,
        patient_status_id:
          this.params1.clue_status_id === "8" ? this.params1.patientStatus : "",
        user_name:
          this.params1.clue_status_id === "8" ? this.params1.userName : "",
        age: this.params1.clue_status_id === "8" ? this.params1.age : "",
        birthday: this.params1.clue_status_id === "8" ? this.birthdays : "",
        patient_diseases_id:
          this.params1.clue_status_id === "8" ? this.params1.oneDiseases : "",
        patient_diseases_child_id:
          this.params1.clue_status_id === "8" ? this.params1.twoDiseases : "",
        patient_remake:
          this.params1.clue_status_id === "8" ? this.params1.remark : "",
        city_id:
          this.params1.clue_status_id === "8" ? this.params1.city_id : "",
        appointment_day:
          this.params1.clue_status_id === "8" &&
          this.params1.patientStatus === "1"
            ? parseInt(new Date(this.DatePicker1).getTime() / 1000)
            : "",
        gender: this.params1.clue_status_id === "8" ? this.params1.sex : "",
        // city_name: this.params1.city
        //     ? this.optionscity.filter(
        //         (ee) => ee.value === this.params1.city
        //     )[0].label
        //     : "",
        wechat_id:
          this.params1.clue_status_id === "8" ? this.params1.weChartNum : "",
        mobile: this.params1.clue_status_id === "8" ? this.params1.mobile : "",
        body_parts_id:
          this.params1.clue_status_id === "8"
            ? this.params1.bodyPart.join(",")
            : "",
      };
      this.remarksloading = true;
      cluecallcontact(params)
        .then(() => {
          this.city_id = [];
          this.remarksloading = false;
          this.askData();
          this.$Message.success("联系成功!");
          this.contactClue = false;
          this.diseasesArr2 = [];
          this.params1 = {
            id: undefined,
            clue_status_id: "8",
            remark: "",
            day: 1,
            day1: 0,
            bodyPart: [],
            userName: "",
            weChartNum: "",
            mobile: "",
            age: null,
            birthday: "",
            sex: "",
            city_id: "",
            oneDiseases: "",
            twoDiseases: "",
            patientStatus: "2",
          };
          this.$refs.formItem.resetFields();
        })
        .catch(() => {
          this.remarksloading = false;
        });
    },
    blurday(num) {
      this.DatePicker = this.$blurday(num);
    },
    changeday(date) {
      this.params1.day = this.$changeday(date);
    },
    getDatas: lodash.debounce(function(params) {
      if (this.optionscity.every((ee) => ee.label !== params)) {
        this.loadingcity = true;
        patientindexsearchcity({
          keywords: params,
        }).then((res) => {
          this.$nextTick(() => {
            this.loadingcity = false;
            this.optionscity = Object.freeze(
              res.list.map((ee) => {
                return {
                  value: ee.value + "," + params,
                  label: ee.label,
                };
              })
            );
            // this.$refs.citySearch.isFocused = false;
          });
        });
      }
    }, 700),
    remoteMethod(query) {
      if (query !== "") {
        this.getDatas(query);
      } else {
        this.optionscity = [];
      }
    },
    blurday1(num) {
      this.DatePicker1 = this.$blurday(num);
    },
    changeday1(date) {
      this.params1.day1 = this.$changeday(date);
    },
    cancel() {
      const audio = document.getElementById("audio");
      if (this.musicurl !== "") {
        audio.pause();
      }
      this.musicurl = "";
      this.model1 = 1;
    },
    changeaudio(model1) {
      const audio = document.getElementById("audio");
      audio.playbackRate = model1;
    },
    askDatacheck() {
      this.params.have_repeat = 0;
      this.searchData.project.forEach((item) => {
        if (item.id === 8) {
          item.value.forEach((its) => {
            if (its === 3) {
              this.params.have_repeat = 1;
            }
          });
        } else if (item.id === 5) {
          item.value = ["", ""];
          this.params.start_time = "";
          this.params.end_time = "";
        }
      });
      this.askData();
    },
  },
};
</script>
<style scoped>
.person {
  color: #999;
}

.repeatColor {
  color: red;
}
</style>
